package com.icode.service.impl.house;

import com.icode.core.dto.manager.SellManagerDTO;
import com.icode.core.model.manage.SellManager;
import com.icode.core.shared.SellManagerHandle;
import com.icode.dao.SellManagerDao;
import com.icode.service.house.SellManagerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xianfei
 * Date: 15-8-15
 * Time: 上午10:49
 * To change this template use File | Settings | File Templates.
 */
@Service("sellManagerService")
@Transactional
public class SellManagerServiceImpl implements SellManagerService {

    @Autowired
    private SellManagerDao sellManagerDao;

    @Override
    @Transactional
    public void saveOrUpdateSell(SellManagerDTO sellManagerDTO) {
        if ("".equals(sellManagerDTO.getGuid())) {
            SellManager isExist = sellManagerDao.findSellIsExist(sellManagerDTO.getArea());
            if (isExist == null) {
                SellManager sellManager = SellManagerDTO.toSellManager(sellManagerDTO);
                sellManagerDao.saveOrUpdate(sellManager);
            }
        } else {
            SellManager sellManager = sellManagerDao.findByGuid(SellManager.class, sellManagerDTO.getGuid());
            sellManager.initSellManager(sellManagerDTO);
        }
    }

    @Override
    @Transactional
    public List<SellManagerDTO> findSellByAll() {
        List<SellManager> sellManagers = sellManagerDao.findSellManagerByAll();
        List<SellManagerDTO> sellManagerDTOs = SellManagerDTO.toDTOs(sellManagers);
        return sellManagerDTOs;
    }

    @Override
    @Transactional
    public SellManagerDTO findSellByGuid(String sellGuid) {
        SellManager sellManager = sellManagerDao.findByGuid(SellManager.class, sellGuid);
        SellManagerDTO sellManagerDTO = SellManagerDTO.toDTO(sellManager);
        return sellManagerDTO;
    }

    @Override
    @Transactional
    public boolean operateSell(String sellGuid, String type) {
        boolean result = true;
        try {
            SellManager sellManager = sellManagerDao.findByGuid(SellManager.class, sellGuid);
            SellManagerHandle.operate(sellManager, type);
        } catch (Exception e) {
            result = false;
        }
        return result;
    }
}
